Page({
  data: {
    imageList: []
  },

  // 选择单张图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      success: (res) => {
        this.processImages(res.tempFilePaths);
      }
    });
  },

  // 批量选择图片
  chooseBatchImages() {
    wx.chooseImage({
      count: 9,
      success: (res) => {
        this.processImages(res.tempFilePaths);
      }
    });
  },

  // 处理图片 - 本地版本
  processImages(tempFilePaths) {
    tempFilePaths.forEach(path => {
      const imageItem = {
        original: path,
        loading: true
      };
      
      this.setData({
        imageList: [...this.data.imageList, imageItem]
      });

      // 模拟处理延迟，实际项目中这里会调用真实的API
      setTimeout(() => {
        const imageList = this.data.imageList;
        const index = imageList.findIndex(item => item.original === path);
        if (index !== -1) {
          imageList[index].loading = false;
          // 这里暂时返回原图，后续可以替换成真实的API调用
          imageList[index].pixelated = path;
          this.setData({ imageList });
          
          wx.showToast({
            title: '转换完成',
            icon: 'success'
          });
        }
      }, 1500); // 模拟1.5秒的处理时间
    });
  },

  // 保存图片到相册
  saveImage(e) {
    const url = e.currentTarget.dataset.url;
    wx.saveImageToPhotosAlbum({
      filePath: url,
      success: () => {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        console.error('保存失败：', err);
        if (err.errMsg.includes('auth deny')) {
          wx.showModal({
            title: '提示',
            content: '需要您授权保存图片到相册',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting({
                  success: (settingRes) => {
                    if (settingRes.authSetting['scope.writePhotosAlbum']) {
                      this.saveImage(e); // 重新尝试保存
                    }
                  }
                });
              }
            }
          });
        } else {
          wx.showToast({
            title: '保存失败',
            icon: 'none'
          });
        }
      }
    });
  }
}); 